const AV = require("leanengine")

const User = AV.Object.extend('User')

let UserModel = {}


UserModel.login = async (req, res) => {
    const _user = {
        username: req.body.username,
        password: req.body.password
    }

    if (!_user.username.trim() && !_user.password.trim()) {
        res.send('用户名和密码不可为空')
    }

    AV.User.logIn(_user.username, _user.password).then(function (loginedUser) {
        res.send(loginedUser);
    }, function (error) {
        res.send(error)
    })
}

UserModel.register = async (req, res) => {

    let user = new User();
    user.set('username', req.body.username)
    user.set('password', req.body.password)
    user.set('tel', req.body.tel)
    user.set('email', req.body.email)
    user.set('name', req.body.name)

    user.signUp().then(function (register) {
        res.send(register);
    }, function (error) {
        res.send(error)
    })
}

UserModel.updatePassword = async (req, res) => {
    console.log(id, 'id信息')
    let id = req.body.id
    let oldPassword = req.body.oldPassword
    let newPassword = req.body.newPassword
    let user = AV.Object.createWithoutData('User', id);
    user.fetch().then(function () {
        let _password = user.get('password')
        if (_password === oldPassword) {
            user.set('password', newPassword)
            user.save()
            res.send("更新密码成功")
        } else {
            res.send("更新密码失败")
        }
    }, function (error) {
        res.send(error)
    })
}

module.exports = UserModel